package com.gec.content.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.gec.mall.pojo.RespBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author: li
 * @Date: 2023/2/6
 * @PACKAGE_NAME:com.gec.content.controller
 * @Project_Name:mall-parent
 * @VERSION: 1.0.0
 */
@RestController
@RequestMapping("/fileUpload")
public class UploadController {
    @Value(("${oss.bucketName}"))
    private String bucketName;

    @Value(("${oss.endpoint}"))
    private String endpoint;

    @Value(("${oss.accessKey}"))
    private String accessKey;

    @Value(("${oss.secretKey}"))
    private String secretKey;

    @Value(("${oss.bucketEndpoint}"))
    private String bucketEndpoint;

    @PostMapping("/uploadFile")
    public RespBean uploadFile(MultipartFile file){
        //创建ossClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint,accessKey,secretKey);
        //创建bucket
        if (ossClient.doesBucketExist(bucketName)){
            System.out.println("您已创建,bucketName: " + bucketName);
        }else {
            ossClient.createBucket(bucketName);
        }

        //设计存储对象
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String filename = file.getOriginalFilename();
        String objectName = sdf.format(new Date()) + "/" + filename;

        try {
            ossClient.putObject(bucketName,objectName,file.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        String httpUrl = bucketEndpoint + "/" +objectName;
        return RespBean.ok(httpUrl,true);
    }
}
